<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div class="settings-page">
    <div class="page-container">
      <!-- 页面标题 -->
      <div class="page-header">
        <div class="header-left">
          <el-button @click="$router.back()" :icon="ArrowLeft" circle />
          <div class="header-info">
            <h1>设置</h1>
            <p>管理您的账户设置和应用偏好</p>
          </div>
        </div>
      </div>

      <!-- 设置内容 -->
      <div class="settings-content">
        <!-- 账户设置 -->
        <div class="setting-section">
          <div class="section-header">
            <h3><el-icon><User /></el-icon> 账户设置</h3>
            <p>管理您的个人信息和账户安全</p>
          </div>

          <div class="setting-items">
            <div class="setting-item">
              <div class="item-info">
                <div class="item-icon">
                  <el-icon><Edit /></el-icon>
                </div>
                <div class="item-content">
                  <div class="item-title">个人资料</div>
                  <div class="item-description">编辑您的基本信息、头像和简介</div>
                </div>
              </div>
              <div class="item-action">
                <el-button @click="$router.push('/profile/edit')" :icon="ArrowRight">
                  编辑
                </el-button>
              </div>
            </div>

            <div class="setting-item">
              <div class="item-info">
                <div class="item-icon">
                  <el-icon><Lock /></el-icon>
                </div>
                <div class="item-content">
                  <div class="item-title">修改密码</div>
                  <div class="item-description">定期更新密码以保证账户安全</div>
                </div>
              </div>
              <div class="item-action">
                <el-button @click="showPasswordDialog = true" :icon="ArrowRight">
                  修改
                </el-button>
              </div>
            </div>

            <div class="setting-item">
              <div class="item-info">
                <div class="item-icon">
                  <el-icon><Phone /></el-icon>
                </div>
                <div class="item-content">
                  <div class="item-title">手机绑定</div>
                  <div class="item-description">
                    {{ userStore.userInfo?.phone ? `已绑定 ${hidePhone(userStore.userInfo.phone)}` : '未绑定手机号' }}
                  </div>
                </div>
              </div>
              <div class="item-action">
                <el-button :icon="ArrowRight">
                  {{ userStore.userInfo?.phone ? '更换' : '绑定' }}
                </el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 应用设置 -->
        <div class="setting-section">
          <div class="section-header">
            <h3><el-icon><Setting /></el-icon> 应用设置</h3>
            <p>自定义您的使用体验</p>
          </div>

          <div class="setting-items">
            <div class="setting-item">
              <div class="item-info">
                <div class="item-icon">
                  <el-icon><Sunny /></el-icon>
                </div>
                <div class="item-content">
                  <div class="item-title">主题模式</div>
                  <div class="item-description">选择浅色或深色主题</div>
                </div>
              </div>
              <div class="item-action">
                <el-switch
                  v-model="darkMode"
                  @change="handleThemeChange"
                  active-text="深色"
                  inactive-text="浅色"
                />
              </div>
            </div>

            <div class="setting-item">
              <div class="item-info">
                <div class="item-icon">
                  <el-icon><Globe /></el-icon>
                </div>
                <div class="item-content">
                  <div class="item-title">语言设置</div>
                  <div class="item-description">选择界面显示语言</div>
                </div>
              </div>
              <div class="item-action">
                <el-select v-model="language" @change="handleLanguageChange" style="width: 120px;">
                  <el-option label="简体中文" value="zh-CN" />
                  <el-option label="繁体中文" value="zh-TW" />
                  <el-option label="English" value="en" />
                </el-select>
              </div>
            </div>

            <div class="setting-item">
              <div class="item-info">
                <div class="item-icon">
                  <el-icon><VideoPlay /></el-icon>
                </div>
                <div class="item-content">
                  <div class="item-title">视频自动播放</div>
                  <div class="item-description">在教程页面自动播放视频</div>
                </div>
              </div>
              <div class="item-action">
                <el-switch
                  v-model="autoPlayVideo"
                  @change="handleAutoPlayChange"
                />
              </div>
            </div>

            <div class="setting-item">
              <div class="item-info">
                <div class="item-icon">
                  <el-icon><Download /></el-icon>
                </div>
                <div class="item-content">
                  <div class="item-title">离线下载</div>
                  <div class="item-description">允许下载教程进行离线学习</div>
                </div>
              </div>
              <div class="item-action">
                <el-switch
                  v-model="allowDownload"
                  @change="handleDownloadChange"
                />
              </div>
            </div>
          </div>
        </div>

        <!-- 通知设置 -->
        <div class="setting-section">
          <div class="section-header">
            <h3><el-icon><Bell /></el-icon> 通知设置</h3>
            <p>管理您接收的通知类型</p>
          </div>

          <div class="setting-items">
            <div class="setting-item">
              <div class="item-info">
                <div class="item-icon">
                  <el-icon><Message /></el-icon>
                </div>
                <div class="item-content">
                  <div class="item-title">系统通知</div>
                  <div class="item-description">接收系统消息和重要公告</div>
                </div>
              </div>
              <div class="item-action">
                <el-switch
                  v-model="notifications.system"
                  @change="saveNotificationSettings"
                />
              </div>
            </div>

            <div class="setting-item">
              <div class="item-info">
                <div class="item-icon">
                  <el-icon><Star /></el-icon>
                </div>
                <div class="item-content">
                  <div class="item-title">推荐通知</div>
                  <div class="item-description">接收新教程和内容推荐</div>
                </div>
              </div>
              <div class="item-action">
                <el-switch
                  v-model="notifications.recommendation"
                  @change="saveNotificationSettings"
                />
              </div>
            </div>

            <div class="setting-item">
              <div class="item-info">
                <div class="item-icon">
                  <el-icon><Trophy /></el-icon>
                </div>
                <div class="item-content">
                  <div class="item-title">学习提醒</div>
                  <div class="item-description">提醒您继续未完成的学习</div>
                </div>
              </div>
              <div class="item-action">
                <el-switch
                  v-model="notifications.study"
                  @change="saveNotificationSettings"
                />
              </div>
            </div>

            <div class="setting-item">
              <div class="item-info">
                <div class="item-icon">
                  <el-icon><ChatLineSquare /></el-icon>
                </div>
                <div class="item-content">
                  <div class="item-title">互动通知</div>
                  <div class="item-description">接收点赞、评论等互动消息</div>
                </div>
              </div>
              <div class="item-action">
                <el-switch
                  v-model="notifications.interaction"
                  @change="saveNotificationSettings"
                />
              </div>
            </div>
          </div>
        </div>

        <!-- 隐私设置 -->
        <div class="setting-section">
          <div class="section-header">
            <h3><el-icon><View /></el-icon> 隐私设置</h3>
            <p>控制您的信息显示和隐私保护</p>
          </div>

          <div class="setting-items">
            <div class="setting-item">
              <div class="item-info">
                <div class="item-icon">
                  <el-icon><UserFilled /></el-icon>
                </div>
                <div class="item-content">
                  <div class="item-title">个人资料可见性</div>
                  <div class="item-description">控制其他用户能看到的信息</div>
                </div>
              </div>
              <div class="item-action">
                <el-select v-model="privacy.profileVisibility" style="width: 120px;">
                  <el-option label="公开" value="public" />
                  <el-option label="仅好友" value="friends" />
                  <el-option label="私密" value="private" />
                </el-select>
              </div>
            </div>

            <div class="setting-item">
              <div class="item-info">
                <div class="item-icon">
                  <el-icon><Document /></el-icon>
                </div>
                <div class="item-content">
                  <div class="item-title">学习记录可见性</div>
                  <div class="item-description">是否公开显示您的学习记录</div>
                </div>
              </div>
              <div class="item-action">
                <el-switch
                  v-model="privacy.showStudyRecord"
                  @change="savePrivacySettings"
                />
              </div>
            </div>

            <div class="setting-item">
              <div class="item-info">
                <div class="item-icon">
                  <el-icon><Search /></el-icon>
                </div>
                <div class="item-content">
                  <div class="item-title">搜索可发现</div>
                  <div class="item-description">允许其他用户搜索到您</div>
                </div>
              </div>
              <div class="item-action">
                <el-switch
                  v-model="privacy.allowSearch"
                  @change="savePrivacySettings"
                />
              </div>
            </div>
          </div>
        </div>

        <!-- 数据管理 -->
        <div class="setting-section">
          <div class="section-header">
            <h3><el-icon><FolderOpened /></el-icon> 数据管理</h3>
            <p>管理您的数据和存储</p>
          </div>

          <div class="setting-items">
            <div class="setting-item">
              <div class="item-info">
                <div class="item-icon">
                  <el-icon><Download /></el-icon>
                </div>
                <div class="item-content">
                  <div class="item-title">导出数据</div>
                  <div class="item-description">下载您的个人数据副本</div>
                </div>
              </div>
              <div class="item-action">
                <el-button @click="exportData" :loading="exporting">
                  导出
                </el-button>
              </div>
            </div>

            <div class="setting-item">
              <div class="item-info">
                <div class="item-icon">
                  <el-icon><Delete /></el-icon>
                </div>
                <div class="item-content">
                  <div class="item-title">清除缓存</div>
                  <div class="item-description">清除本地缓存数据</div>
                </div>
              </div>
              <div class="item-action">
                <el-button @click="clearCache" :loading="clearing">
                  清除
                </el-button>
              </div>
            </div>

            <div class="setting-item danger">
              <div class="item-info">
                <div class="item-icon">
                  <el-icon><Warning /></el-icon>
                </div>
                <div class="item-content">
                  <div class="item-title">删除账户</div>
                  <div class="item-description">永久删除您的账户和所有数据</div>
                </div>
              </div>
              <div class="item-action">
                <el-button type="danger" @click="showDeleteDialog = true">
                  删除账户
                </el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 关于 -->
        <div class="setting-section">
          <div class="section-header">
            <h3><el-icon><InfoFilled /></el-icon> 关于</h3>
            <p>应用信息和帮助</p>
          </div>

          <div class="setting-items">
            <div class="setting-item">
              <div class="item-info">
                <div class="item-icon">
                  <el-icon><Notebook /></el-icon>
                </div>
                <div class="item-content">
                  <div class="item-title">版本信息</div>
                  <div class="item-description">v1.0.0</div>
                </div>
              </div>
            </div>

            <div class="setting-item">
              <div class="item-info">
                <div class="item-icon">
                  <el-icon><QuestionFilled /></el-icon>
                </div>
                <div class="item-content">
                  <div class="item-title">帮助与支持</div>
                  <div class="item-description">使用帮助和常见问题</div>
                </div>
              </div>
              <div class="item-action">
                <el-button @click="showHelp" :icon="ArrowRight">
                  查看
                </el-button>
              </div>
            </div>

            <div class="setting-item">
              <div class="item-info">
                <div class="item-icon">
                  <el-icon><Document /></el-icon>
                </div>
                <div class="item-content">
                  <div class="item-title">用户协议</div>
                  <div class="item-description">查看完整的用户协议</div>
                </div>
              </div>
              <div class="item-action">
                <el-button @click="showAgreement" :icon="ArrowRight">
                  查看
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 修改密码对话框 -->
    <el-dialog v-model="showPasswordDialog" title="修改密码" width="400px">
      <el-form ref="passwordFormRef" :model="passwordForm" :rules="passwordRules" label-width="100px">
        <el-form-item label="当前密码" prop="oldPassword">
          <el-input
            v-model="passwordForm.oldPassword"
            type="password"
            placeholder="请输入当前密码"
            show-password
          />
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showPasswordDialog = false">取消</el-button>
          <el-button type="primary" @click="handlePasswordChange" :loading="passwordLoading">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 删除账户确认对话框 -->
    <el-dialog v-model="showDeleteDialog" title="删除账户" width="500px">
      <div class="delete-warning">
        <el-icon class="warning-icon"><Warning /></el-icon>
        <div class="warning-content">
          <h4>您确定要删除账户吗？</h4>
          <p>此操作将永久删除您的账户和所有相关数据，包括：</p>
          <ul>
            <li>个人资料和设置</li>
            <li>学习记录和进度</li>
            <li>收藏的内容</li>
            <li>所有学习笔记</li>
          </ul>
          <p class="warning-text">此操作无法撤销，请谨慎考虑。</p>
        </div>
      </div>

      <el-form :model="deleteForm" ref="deleteFormRef">
        <el-form-item
          prop="confirmText"
          :rules="[{ validator: validateDeleteConfirm, trigger: 'blur' }]"
        >
          <template #label>
            <span>请输入 <strong>"删除账户"</strong> 以确认：</span>
          </template>
          <el-input v-model="deleteForm.confirmText" placeholder="删除账户" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showDeleteDialog = false">取消</el-button>
          <el-button type="danger" @click="handleDeleteAccount" :loading="deleting">
            确定删除
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import {
  ArrowLeft, User, Edit, Lock, Phone, ArrowRight, Setting, Sunny, Globe,
  VideoPlay, Download, Bell, Message, Star, Trophy, ChatLineSquare,
  View, UserFilled, Document, Search, FolderOpened, Delete, Warning,
  InfoFilled, Notebook, QuestionFilled
} from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()

// 对话框状态
const showPasswordDialog = ref(false)
const showDeleteDialog = ref(false)

// 加载状态
const passwordLoading = ref(false)
const deleting = ref(false)
const exporting = ref(false)
const clearing = ref(false)

// 表单引用
const passwordFormRef = ref<FormInstance>()
const deleteFormRef = ref<FormInstance>()

// 应用设置
const darkMode = ref(false)
const language = ref('zh-CN')
const autoPlayVideo = ref(true)
const allowDownload = ref(true)

// 通知设置
const notifications = reactive({
  system: true,
  recommendation: true,
  study: true,
  interaction: false
})

// 隐私设置
const privacy = reactive({
  profileVisibility: 'public',
  showStudyRecord: true,
  allowSearch: true
})

// 密码表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 删除账户表单
const deleteForm = reactive({
  confirmText: ''
})

// 密码验证规则
const passwordRules: FormRules = {
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 删除确认验证
const validateDeleteConfirm = (rule: any, value: any, callback: any) => {
  if (value !== '删除账户') {
    callback(new Error('请输入正确的确认文字'))
  } else {
    callback()
  }
}

// 初始化设置
const initSettings = () => {
  // 从本地存储加载设置
  const savedSettings = localStorage.getItem('userSettings')
  if (savedSettings) {
    const settings = JSON.parse(savedSettings)
    darkMode.value = settings.darkMode || false
    language.value = settings.language || 'zh-CN'
    autoPlayVideo.value = settings.autoPlayVideo !== false
    allowDownload.value = settings.allowDownload !== false
    Object.assign(notifications, settings.notifications || notifications)
    Object.assign(privacy, settings.privacy || privacy)
  }
}

// 保存设置到本地存储
const saveSettings = () => {
  const settings = {
    darkMode: darkMode.value,
    language: language.value,
    autoPlayVideo: autoPlayVideo.value,
    allowDownload: allowDownload.value,
    notifications: { ...notifications },
    privacy: { ...privacy }
  }
  localStorage.setItem('userSettings', JSON.stringify(settings))
}

// 主题切换
const handleThemeChange = (value: boolean) => {
  // TODO: 实现主题切换逻辑
  document.documentElement.classList.toggle('dark', value)
  saveSettings()
  ElMessage.success(value ? '已切换到深色主题' : '已切换到浅色主题')
}

// 语言切换
const handleLanguageChange = (value: string) => {
  // TODO: 实现国际化语言切换
  saveSettings()
  ElMessage.success('语言设置已更新')
}

// 自动播放设置
const handleAutoPlayChange = () => {
  saveSettings()
  ElMessage.success('视频播放设置已更新')
}

// 下载设置
const handleDownloadChange = () => {
  saveSettings()
  ElMessage.success('下载设置已更新')
}

// 保存通知设置
const saveNotificationSettings = () => {
  saveSettings()
  ElMessage.success('通知设置已更新')
}

// 保存隐私设置
const savePrivacySettings = () => {
  saveSettings()
  ElMessage.success('隐私设置已更新')
}

// 修改密码
const handlePasswordChange = async () => {
  if (!passwordFormRef.value) return

  try {
    await passwordFormRef.value.validate()
    passwordLoading.value = true

    await userStore.changePassword({
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword,
      confirmPassword: passwordForm.confirmPassword
    })

    ElMessage.success('密码修改成功，请重新登录')
    showPasswordDialog.value = false

    // 清空表单
    Object.assign(passwordForm, {
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    })

    // 跳转到登录页
    setTimeout(() => {
      userStore.logout()
      router.push('/login')
    }, 1500)
  } catch (error) {
    console.error('修改密码失败:', error)
  } finally {
    passwordLoading.value = false
  }
}

// 导出数据
const exportData = async () => {
  exporting.value = true
  try {
    // TODO: 实现数据导出功能
    await new Promise(resolve => setTimeout(resolve, 2000))
    ElMessage.success('数据导出成功，请检查下载文件夹')
  } catch (error) {
    ElMessage.error('数据导出失败')
  } finally {
    exporting.value = false
  }
}

// 清除缓存
const clearCache = async () => {
  clearing.value = true
  try {
    // 清除本地存储
    const keysToKeep = ['token', 'userInfo', 'userSettings']
    const allKeys = Object.keys(localStorage)
    allKeys.forEach(key => {
      if (!keysToKeep.includes(key)) {
        localStorage.removeItem(key)
      }
    })

    // 清除会话存储
    sessionStorage.clear()

    await new Promise(resolve => setTimeout(resolve, 1000))
    ElMessage.success('缓存清除成功')
  } catch (error) {
    ElMessage.error('缓存清除失败')
  } finally {
    clearing.value = false
  }
}

// 删除账户
const handleDeleteAccount = async () => {
  if (!deleteFormRef.value) return

  try {
    await deleteFormRef.value.validate()
    deleting.value = true

    // TODO: 调用删除账户API
    await new Promise(resolve => setTimeout(resolve, 2000))

    ElMessage.success('账户已删除')
    showDeleteDialog.value = false

    // 清除所有本地数据
    localStorage.clear()
    sessionStorage.clear()

    // 跳转到首页
    router.push('/')
  } catch (error) {
    console.error('删除账户失败:', error)
  } finally {
    deleting.value = false
  }
}

// 显示帮助
const showHelp = () => {
  ElMessage.info('帮助功能开发中')
}

// 显示用户协议
const showAgreement = () => {
  ElMessage.info('用户协议功能开发中')
}

// 隐藏手机号
const hidePhone = (phone: string) => {
  if (!phone || phone.length !== 11) return phone
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
}

onMounted(() => {
  initSettings()
})
</script>

<style scoped>
.settings-page {
  min-height: 100vh;
  background: #f5f5f5;
}

.page-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

/* 页面头部 */
.page-header {
  background: #fff;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-info h1 {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 4px;
}

.header-info p {
  color: #666;
  font-size: 14px;
}

/* 设置内容 */
.settings-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.setting-section {
  background: #fff;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.section-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.section-header h3 {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.section-header p {
  color: #666;
  font-size: 14px;
}

.setting-items {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.setting-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  transition: all 0.3s;
}

.setting-item:hover {
  background: #fafafa;
  border-color: #e0e0e0;
}

.setting-item.danger {
  border-color: #ffebee;
  background: #fffbfb;
}

.setting-item.danger:hover {
  border-color: #ffcdd2;
  background: #ffebee;
}

.item-info {
  display: flex;
  align-items: center;
  gap: 16px;
  flex: 1;
}

.item-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #f0f8ff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  color: #2196f3;
}

.setting-item.danger .item-icon {
  background: #ffebee;
  color: #f44336;
}

.item-content {
  flex: 1;
}

.item-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.item-description {
  font-size: 14px;
  color: #666;
  line-height: 1.4;
}

.item-action {
  margin-left: 16px;
}

/* 删除警告 */
.delete-warning {
  display: flex;
  gap: 16px;
  margin-bottom: 24px;
}

.warning-icon {
  font-size: 48px;
  color: #ff9800;
  flex-shrink: 0;
}

.warning-content h4 {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 12px;
}

.warning-content p {
  margin-bottom: 12px;
  color: #666;
  line-height: 1.6;
}

.warning-content ul {
  margin: 12px 0;
  padding-left: 20px;
  color: #666;
}

.warning-content li {
  margin-bottom: 4px;
}

.warning-text {
  font-weight: bold;
  color: #f44336;
}

/* 对话框 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-container {
    padding: 16px;
  }

  .page-header {
    padding: 20px;
  }

  .setting-section {
    padding: 20px;
  }

  .setting-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }

  .item-info {
    width: 100%;
  }

  .item-action {
    margin-left: 0;
    align-self: stretch;
  }

  .item-action .el-button {
    width: 100%;
  }

  .delete-warning {
    flex-direction: column;
    text-align: center;
  }
}
</style>
